<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="配置名称" prop="configName">
        <el-input v-model="queryParams.configName" placeholder="请输入配置名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="网站名称" prop="siteName">
        <el-input v-model="queryParams.siteName" placeholder="请输入网站名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="enabled">
        <el-select v-model="queryParams.enabled" placeholder="配置状态" clearable style="width: 240px">
          <el-option label="启用" :value="true" />
          <el-option label="禁用" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['system:crawler:config:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:crawler:config:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:crawler:config:remove']">删除</el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="配置名称" align="center" prop="configName" :show-overflow-tooltip="true" />
      <el-table-column label="网站名称" align="center" prop="siteName" :show-overflow-tooltip="true" />
      <el-table-column label="基础URL" align="center" prop="baseUrl" :show-overflow-tooltip="true" />
      <el-table-column label="最大页数" align="center" prop="maxPages" width="100" />
      <el-table-column label="状态" align="center" prop="enabled" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.enabled ? 'success' : 'info'">
            {{ scope.row.enabled ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:crawler:config:edit']">修改</el-button>
          <el-button link type="primary" icon="VideoPlay" @click="handleTest(scope.row)"
            v-hasPermi="['system:crawler:config:test']">测试</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:crawler:config:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改爬虫配置对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="configRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配置名称" prop="configName">
              <el-input v-model="form.configName" placeholder="请输入配置名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="网站名称" prop="siteName">
              <el-input v-model="form.siteName" placeholder="请输入网站名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="基础URL" prop="baseUrl">
              <el-input v-model="form.baseUrl" placeholder="请输入基础URL" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="列表页URL模板" prop="listUrlTemplate">
              <el-input v-model="form.listUrlTemplate" placeholder="如: https://example.com/list?page={page}" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">选择器配置</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="列表项选择器" prop="listSelector">
              <el-input v-model="form.listSelector" placeholder="如: .policy-item" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="标题选择器" prop="titleSelector">
              <el-input v-model="form.titleSelector" placeholder="如: .title" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="链接选择器" prop="linkSelector">
              <el-input v-model="form.linkSelector" placeholder="如: .a" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="内容选择器" prop="contentSelector">
              <el-input v-model="form.contentSelector" placeholder="如: .content" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文号选择器" prop="documentNumberSelector">
              <el-input v-model="form.documentNumberSelector" placeholder="如: .doc-number" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="日期选择器" prop="dateSelector">
              <el-input v-model="form.dateSelector" placeholder="如: .date" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">执行配置</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="最大页数" prop="maxPages">
              <el-input-number v-model="form.maxPages" :min="1" :max="1000" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="请求间隔(毫秒)" prop="requestInterval">
              <el-input-number v-model="form.requestInterval" :min="1000" :max="10000" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="超时时间(毫秒)" prop="timeout">
              <el-input-number v-model="form.timeout" :min="5000" :max="30000" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="User-Agent" prop="userAgent">
              <el-input v-model="form.userAgent" placeholder="浏览器标识" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="enabled">
              <el-radio-group v-model="form.enabled">
                <el-radio :value="true">启用</el-radio>
                <el-radio :value="false">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
          <el-button type="success" @click="testConfig">测试配置</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="CrawlerConfig">
import { listConfig, getConfig, delConfig, addConfig, updateConfig, testConfig as testConfigApi } from "@/api/system/crawler/config";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const configList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");



const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    configName: undefined,
    siteName: undefined,
    enabled: undefined
  },
  rules: {
    configName: [
      { required: true, message: "配置名称不能为空", trigger: "blur" }
    ],
    siteName: [
      { required: true, message: "网站名称不能为空", trigger: "blur" }
    ],
    baseUrl: [
      { required: true, message: "基础URL不能为空", trigger: "blur" }
    ],
    listSelector: [
      { required: true, message: "列表项选择器不能为空", trigger: "blur" }
    ],
    titleSelector: [
      { required: true, message: "标题选择器不能为空", trigger: "blur" }
    ],
    linkSelector: [
      { required: true, message: "链接选择器不能为空", trigger: "blur" }
    ],
    contentSelector: [
      { required: true, message: "内容选择器不能为空", trigger: "blur" }
    ]
  },

});

const { queryParams, form, rules } = toRefs(data);

/** 查询爬虫配置列表 */
function getList() {
  loading.value = true;
  listConfig(queryParams.value).then(response => {
    configList.value = response.rows || [];
    total.value = Number(response.total) || 0;
    loading.value = false;
  }).catch(error => {
    console.error('获取列表失败:', error);
    configList.value = [];
    total.value = 0;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加爬虫配置";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value[0];
  getConfig(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改爬虫配置";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["configRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateConfig(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addConfig(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const configIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除爬虫配置编号为"' + configIds + '"的数据项？').then(function() {
    return delConfig(configIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 测试配置按钮操作 */
function handleTest(row) {
  proxy.$modal.confirm('是否确认测试配置"' + row.configName + '"？').then(function() {
    return testConfigApi(row);
  }).then(() => {
    proxy.$modal.msgSuccess("配置测试通过");
  }).catch(() => {
    proxy.$modal.msgError("配置测试失败");
  });
}



/** 测试配置 */
function testConfig() {
  proxy.$refs["configRef"].validate(valid => {
    if (valid) {
      testConfigApi(form.value).then(response => {
        proxy.$modal.msgSuccess("配置测试通过");
      }).catch(() => {
        proxy.$modal.msgError("配置测试失败");
      });
    }
  });
}



/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    configName: null,
    siteName: null,
    baseUrl: null,
    listUrlTemplate: null,
    listSelector: null,
    titleSelector: null,
    linkSelector: null,
    contentSelector: null,
    documentNumberSelector: null,
    dateSelector: null,
    maxPages: 1000,
    requestInterval: 2000,
    timeout: 15000,
    userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    enabled: true,
    remark: null
  };
  proxy.resetForm("configRef");
}



getList();
</script>

<style scoped>
</style> 